package com.cn.controller;

import com.cn.cloud.entities.CommonResult;
import com.cn.cloud.entities.People;
import com.cn.service.DtgxPeopleService;
import com.cn.util.JsonUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;
import com.cn.service.PeopleService;

import java.util.concurrent.TimeUnit;

@RestController
@Slf4j
@RequestMapping("/people")
public class PeopleController {

    @Autowired
    private PeopleService peopleService;
    @Autowired
    private DtgxPeopleService dtgxPeopleService;
    @Autowired
    private RedisTemplate<String,People> redisTemplate;

    @Value("${server.port}")
    private String SERVER_PORT;

    @PostMapping("/create") //@RequestBody
    public CommonResult create( People people) {
        int result = peopleService.create(people);
        CommonResult rpcresult = dtgxPeopleService.create(people);
        redisTemplate.opsForValue().set("myKey",people);
        System.out.println(redisTemplate.opsForValue().get("myKey"));
        log.info("插入数据的ID:\t" + people.getId());
        log.info("插入结果：" + result + rpcresult);
        if (result > 0) {
            return new CommonResult(200, "插入数据成功,serverport:" + SERVER_PORT);
        } else {
            return new CommonResult(444, "插入数据失败", null);
        }
    }

    @GetMapping("/get/{id}")
    public CommonResult getPaymentById(@PathVariable("id") Long id) {
        People people = peopleService.getPeopleById(id);
        log.info("***查询结果：" + people+"hhhhhh");
        //查询成功后  使用Redis上锁
        String json = JsonUtils.objectToJson(people);
        String md5 = DigestUtils.md5DigestAsHex(json.getBytes()).toUpperCase();
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(String.valueOf(people.getId()), people, 60 * 5, TimeUnit.SECONDS);
        if (flag) {
            // lock success, start to handle business
            log.debug("{} lock success, start to handle business", md5);
            /*try {
                //mock to handle business
                Thread.sleep(1000 * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }*/
            //end to handle business, need to unlock
            //redisTemplate.delete(md5);
            log.debug("{} unlock success，end to handle business", md5);
            return new CommonResult(200, "查询数据成功,serverport:"+ SERVER_PORT +"--key:"+ String.valueOf(people.getId()));
        } else {
            log.debug("{} lock failure", md5);
            return new CommonResult(444, "try again later,获取失败！", null);
        }
    }


    @PostMapping("/editPeople")
    public CommonResult editPeople(People people,String val) {
        //释放锁
        redisTemplate.delete(val);
        return new CommonResult(200, "编辑数据成功,serverport:"+ SERVER_PORT +"--key:"+ val);
    }




    /**
     * Redis 分布式锁实现 demo
     * @param people
     * @return
     */
    @PostMapping(value = "/createLock")
    public String createLock(People people) {

        String json = JsonUtils.objectToJson(people);
        String md5 = DigestUtils.md5DigestAsHex(json.getBytes()).toUpperCase();

        /*
         * setIfAbsent <=> SET key value [NX] [XX] [EX <seconds>] [PX [millseconds]]
         * set expire time 5 mins
         */
        Boolean flag = redisTemplate.opsForValue().setIfAbsent(md5, people, 60 * 5, TimeUnit.SECONDS);
        if (flag) {
            // lock success, start to handle business
            log.debug("{} lock success, start to handle business", md5);
            try {
                //mock to handle business
                Thread.sleep(1000 * 10);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            //end to handle business, need to unlock
            redisTemplate.delete(md5);
            log.debug("{} unlock success，end to handle business", md5);
            return "SUCCESS";
        } else {
            log.debug("{} lock failure", md5);
            return "try again later";
        }
    }

}
